const i18n = new VueI18n({
    locale: 'zh', // 设置默认
    messages
});
var em = new Vue({
    el: main,
    i18n,
    data: {
        leftNum: 0, //用来判断左侧菜单的样式，选取0位第一个
        menuLefts: [{ //构建的左侧菜单选项
            title: "homeResultDataJsp.observation_dat",
            url: "../img/home/IconRealityS.png"
        }, {
            title: "homeResultDataJsp.Simulation_data",
            url: "../img/home/IconSimulate.png"
        }, {
            title: "homeResultDataJsp.assimilation_data",
            url: "../img/home/IconTonghua.png"
        }],
        //实测数据显示
        realityTableShow: true,
        //实际属性
        reallyProOption: null,
        reallyProValue: null,
        simulationProValue: null,
        //实际时间
        reallyTimeValue: null,
        simulationTimeValue: null,
        //表格数据+分页
        pageCount: 0,
        pageNo: 0,
        tableData: null,
        allData: null,
        //模拟数据
        simulationTableShow: false,
        tierOptionValue: 1,        //层数选项
        taskOption: [],              //任务
        taskOptionValue: "",         //任务选项
        siteTypeOption: null,       //类别
        siteTypeOptionValue: "",    //类别选项
        fileOptionValue: "",         //文件
        siteOptionValue: "DM3",     //观测点数据
        imageTimeValue: null,
        searchText: null,
        compareData: null,
        locals18n: "",
        iframeDivShow: false,
        iframeDivShow1: false,
        echarttype:'duibi',
        dateValue: null,
        selectedsiteValue:null,
        siteValue:null,
        scsj:true,
        loading: true,
        echarttypeoptions:[
            {value:'duibi',label:'对比分析'},
            {value:'yancheng',label:'沿程分析'}
        ],
    },
    created: function () {
        this.getSiteValue(); //获取观测点数据
        //初始化
        try {
            window.parent.toggleLoading();
        } catch (e) {
        }
        //获得全部属性
        this.$http.get('../readMap/findHisDataType.do?type=-1', {emulateJSON: true}).then(function (res) {
            //在前端进行一下分配
            var arrayList = res.data;
            var objectMap = [{"": ""}];
            for (let i = 0; i < arrayList.length; i++) {
                objectMap[arrayList[i].proNamech] = arrayList[i];
            }
            this.compareData = objectMap;
            // console.log(objectMap);
            // console.log(this.compareData["总氮结束吸光度"]);
            that = this
            setTimeout(function() {
                that.loadReality();
            }, 1000);

        });

        this.locals18n = this.common.Initial();
        this.$i18n.locale = this.locals18n;
    },watch: {
        'siteTypeOptionValue': {
            handler(newValue, oldValue) {
                console.log(this.siteTypeOptionValue)
                this.loadDate();
            }
        }, 'dateValue': {
            handler(newValue, oldValue) {
                if (this.siteTypeOptionValue != null && this.siteTypeOptionValue != "") {
                    this.loadDate();
                }
            }
        }
    },
    // watch: {
    //     'tierOptionValue': {
    //         handler(newValue, oldValue) {
    //              console.log(newValue);
    //         }
    //     }
    // },
    methods: {
        //属性值是否超标判断
        warningFormat(row, column) {
            console.log(row);
            //获取属性值，然后比大小
            var name = "";
            var value = "";
            if (column == 1) {
                name = row.hisRemark;
                if (this.locals18n == "en") {
                    name = row.hisPro;
                }
                value = row.hisValue;
            } else if (column == 0) {
                name = row.dataNameCh;
                value = row.dataValue;
            }
            // console.log(this.compareData[name]);
            if (typeof (this.compareData[name]) == "undefined") {
                return "";
            }
            // console.log(value, this.compareData[name].proNormmax);
            return this.panduanValue(value, this.compareData[name]);
        },
        //返回显示的样式
        panduanValue(value, maxValue) {
            //对应的文字
            var zc;
            var jg;
            var cb;
            // console.log(this.locals18n);
            if (this.locals18n == "en") {
                zc = messages.en.homeResultDataJsp.Normal;
                cb = messages.en.homeResultDataJsp.Exceed;
                jg = messages.en.homeResultDataJsp.warning;
            } else {
                zc = messages.zh.homeResultDataJsp.Normal;
                cb = messages.zh.homeResultDataJsp.Exceed;
                jg = messages.zh.homeResultDataJsp.warning;
            }
            //首先看是不是超标
            if (this.judgeRange(maxValue.proRed, value)) {
                return "<span style='color: red'>" + cb + "</span>";
            } else if (this.judgeRange(maxValue.proYellow, value)) {
                return "<span style='color: yellow'>" + jg + "</span>";
            } else if (this.judgeRange(maxValue.proGreen, value)) {
                return "<span style='color: green'>" + zc + "</span>";
            } else {
                return "<span style='color: green'>不超标</span>";
            }
            // if (maxValue == null) {
            //     return "";
            // }
            // if (value > maxValue) {
            //     return "<span style='color: red'>"+cb+"(>" + maxValue + ")</span>";
            // } else {
            //     return zc;
            // }
        },
        judgeRange(range, value) {
            //判断是否在某个区间
            //[+∞,0.06]&[+∞,0.06]
            // console.log(range, value);
            if (typeof (range) == "undefined" || range == null || range == "") {
                return false;
            }
            var maxminArray = range.split("&");
            for (let i = 0; i < maxminArray.length; i++) {
                var maxmin = range.substring(1, maxminArray[i].length - 1).split(",")
                var max = maxmin[0];
                var min = maxmin[1];
                if (max.indexOf("∞") != -1) {
                    //包含最大
                    if (value > min) {
                        return true;
                    } else {
                        return false;
                    }
                } else if (min.indexOf("∞") != -1) {
                    if (value < max) {
                        return true;
                    } else {
                        return false;
                    }
                }
                else {
                    if (value > min && value < max) {
                        return true;
                    } else {
                        return false;
                    }
                }
            }

        },
        loadData() {
            console.log("查询数据")
            //查询模拟数据
            if (this.fileOptionValue != "" && this.siteTypeOptionValue != "" && this.tierOptionValue != "" && this.siteOptionValue != "") {
                var beginDate = "";
                var endDate = "";
                if (this.dateValue != null) {
                    beginDate = this.dateToString(this.dateValue[0]);
                    endDate = this.dateToString(this.dateValue[1]);
                }
                //查询his 里面的数据
                this.$http.get('/readMap/queryHis.do?languageType=' + this.locals18n + '&type=' + this.siteTypeOptionValue + "&trie=" + this.tierOptionValue + "&fileID=" + this.fileOptionValue + "&site=" + this.siteOptionValue + "&beginTime=" + beginDate + "&endTime=" + endDate, {emulateJSON: true}).then(function (res) {
                    this.pageCount = res.data.length;
                    this.allData = res.data;
                    if (res.data.length != 0) {
                        if (res.data[0].id == "000") {
                            this.$message({
                                message: '新数据正在加载中，请稍后重试。',
                                type: 'error'
                            });
                        } else {
                            // this.nowUnit = res.data[0].hisUnit;
                            // var datasChart = this.fromatTimeData(res.data);
                            // var beginDate = this.dateToString(datasChart[0][0]);
                            // var endDate = this.dateToString(datasChart[datasChart.length - 1][0]);
                            // this.loadChart(datasChart, beginDate, endDate);
                        }
                    } else {

                        this.$message({
                            message: '没有数据',
                            type: 'error'
                        });
                    }
                    //表格数据
                    this.tableData = this.fromatTableData(res.data, 1);
                });
            }

        },
        weekly() {
//        	 this.$http.get('/weekly/downLoad.do').then(function (res) {
//        		 console.log(res.data);
//        		 if(res.code=='1'){
//        			 this.$message({
//            			 message: res.msg
//                    });
//        		 }else{
//        			 location.href='/weekly/downLoad.do?id='+res.msg
//        		 }
//        		
//             });
        	location.href='/weekly/downLoad.do'
        		 this.$message({
        			 message: '周报生成中。。。。'
                });	
        },
        loadReality() {
            this.loading=true
            //获得实际数据的table
            console.log(this.reallyProValue);
            console.log(this.reallyTimeValue);
            var beginDate = null,endDate = null;
            if (this.reallyTimeValue != null) {
                beginDate = new Date(this.reallyTimeValue[0]);
                endDate = new Date(this.reallyTimeValue[1]);
            }
            this.$http.get('/hardware/getHarewaredData.do?pre=' + this.reallyProValue.id+'&begDate='+beginDate+'&endDate='+endDate, {emulateJSON: true}).then(function (res) {
                this.pageCount = res.data.length;
                this.allData = res.data;
                if (res.data.length == 0) {
                    this.loading=false
                    this.$message({
                        message: '未查询到数据',
                        type: 'error'
                    });
                } else {
                    this.loading=false
                    this.tableData = this.fromatTableData(res.data, 1);
                }
            });
        },
        loadsimulation() {
            //获得预测数据的table
            console.log(this.simulationProValue);
            console.log(this.simulationTimeValue);
            var beginDate = null,endDate = null;
            if (this.simulationTimeValue != null) {
                beginDate = new Date(this.simulationTimeValue[0]);
                endDate = new Date(this.simulationTimeValue[1]);
            }
            this.$http.get('/hardware/getHarewaredsimulationData.do?pre=' + this.simulationProValue.id+'&begDate='+beginDate+'&endDate='+endDate, {emulateJSON: true}).then(function (res) {
                this.pageCount = res.data.length;
                this.allData = res.data;
                if (res.data.length == 0) {
                    this.$message({
                        message: '未查询到数据',
                        type: 'error'
                    });
                } else {
                    this.tableData = this.fromatTableData(res.data, 1);
                }
            });
        },
        myclass({row,column,rowindex,columnindex}){
            if (rowindex === 2 && columnindex == 5){
                return 'redbackg';
            }
        },
        leftSwitch(index) {
            //上方菜单栏切换事件
            this.leftNum = index;
            for (i = 0; i < this.menuLefts.length; i++) {
                this.menuLefts[i].url = this.menuLefts[i].url.replace("S.png", ".png");
            }
            this.menuLefts[index].url = this.menuLefts[index].url.replace(".png", "S.png");
            //首先全部false
            this.realityTableShow = false;
            this.simulationTableShow = false;
            this.iframeDivShow = false;
            this.iframeDivShow1 = false;
            // this.imageTableShow = false;
            // this.hardwareTableShow=false;
            //然后在逐一打开
            this.tableData = null;
            this.pageCount = 0;
            switch (index) {
                case 0:
                    //实测数据
                    this.scsj = true;
                    this.iframeDivShow= false;
                    this.iframeDivShow1= false;
                    this.loadReality();
                    break;
                case 1:
                    this.scsj = false;
                    this.iframeDivShow= true;
                    this.iframeDivShow1= false;
                    break;
                case 2:
                    console.log("地图查询")
                    //拟合数据
                    // this.imageTableShow = true;
                    //var iframe = document.getElementById("mainIframe")
                    //iframe.src ="../dm3/homeDm3.do";
                    //document.getElementById("mainIframe").src ="../dm3/homeDm3.do";
                    this.scsj = false;
                    this.iframeDivShow= false;
                    this.iframeDivShow1 = true;
                    break;
                default:
                    break;
            }
        },
        // 下面是表格分页的一些东西
        handleCurrentChange(val) {
            //分页的跳转
            this.tableData = this.fromatTableData(this.allData, val);
        }, fromatTableData(data, pageNo) {
            //分页
            var beginNo = (pageNo - 1) * 10;
            var datas = [];
            var lengt = 0;
            if (beginNo + 10 > data.length) {
                lengt = data.length;
            } else {
                lengt = beginNo + 10
            }
            for (let i = beginNo; i < lengt; i++) {
                datas.push(data[i]);
            }
            return datas;
        },
        loadChart(datas, beginDate, endDate,duibidatas,yanchengdatas,danweiy,optiondata) {

            var echarttype = this.echarttype;
            var texts = "";
            var optionValue=this.siteTypeOptionValue.proNamech;
            if("en"==this.locals18n){
                optionValue=this.siteTypeOptionValue.proNameen;
            }
            if (beginDate != null) {
                texts = beginDate + ' - ' + endDate + '      '+ optionValue ;
            }
            var xaxis,yaxis = null;var seriesdata = [];
            var linecolor={'库心':'#e42222'}
            if (echarttype === 'duibi'){
                xaxis = {
                    name:'时间',
                    type: 'time',
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    splitNumber: 20
                };
                yaxis = {
                    type: 'value',
                };
                for (let key in duibidatas) {
                    if (duibidatas.hasOwnProperty(key)) {
                        seriesdata.push({
                            name: key,
                            type: 'line',
                            data: duibidatas[key],
                            // color: linecolor[key]
                        })
                    }
                }
                /*
                                for (let i = 0; i < upDataData[data].length; i++) {
                                    var d = upDataData[data][i];
                                    seriesdata.push({
                                        name: name,
                                        type: 'line',
                                        data: d
                                    })
                                }
                */
            }else {
                xaxis = {
                    name:'站点',
                    type: 'category',
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    },
                    splitNumber: 20
                };
                yaxis = {
                    name: '时间',
                    type: 'value',
                };
                var times = Object.keys(yanchengdatas);
                var bigtime = times[0];
                for (let i = 0; i < times.length; i++) {
                    if (times[i]>bigtime)
                        bigtime = times[i];
                }
                // for (let key in yanchengdatas) {
                //     if (yanchengdatas.hasOwnProperty(key)) {
                seriesdata.push({
                    name: bigtime,
                    type: 'line',
                    data: yanchengdatas[bigtime],
                })
                // }
                // }
            }
            this.myChart = echarts.init(document.getElementById('eChartsDiv'));
            this.myChart.clear();
            option = {
                title: {
                    text: texts,
                    left: 'center'
                },
                /*legend: {
                    data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
                },*/
                tooltip: {
                    trigger: 'axis',

                    axisPointer: {
                        type: 'cross'
                    }
                },
                xAxis: xaxis,
                yAxis: yaxis,
                series: seriesdata/*[
                   /!* {
                        name: optionValue,
                        type: 'line',
                        data: upDataData,
                        color: ["#39CCCC"],
                    },*!/{
                        name: optionValue,
                        type: 'line',
                        data: datas,
                        color: ["#e42222"],
                    },
                ]*/
            };

            var biaozunJson = "";
            /*
                        if (this.siteTypeOptionValue.proRemark.indexOf("NH3_ppm")!=-1) {
                            // console.log("?");
                            option.series.push(this.biaozunFormate(0.06, 'MAX', datas));
                        } else if (this.siteTypeOptionValue.proRemark.indexOf("TN_ppm")!=-1) {
                            // console.log("?1");
                            option.series.push(this.biaozunFormate(1, 'MAX', datas));
                        } else if (this.siteTypeOptionValue .proRemark.indexOf("TP_ppm")!=-1) {
                            // console.log("?2");
                            option.series.push(this.biaozunFormate(0.06, 'MAX', datas));
                        }
            */
            this.myChart.setOption(option);
        },
        fromatTimeData(date) {
            var data = [];
            for (let i = 0; i < date.length; i++) {
                var now = new Date(date[i].dataTime);
                var value = date[i].dataValue;
                var jjson = [now, value];
                data.push(jjson);
            }
            return data;
        },
        fromatTimeDataUploadValue1(date) {
            //处理站点信息｛id:name｝
            var sitemap = {};
            for (let i = 0; i < this.siteValue.length; i++) {
                var site = this.siteValue[i];
                sitemap[site.id] = site.siteName;

            }
            var result = {};var arr = [];
            for (let i = 0; i < date.length; i++) {
                var v = date[i].dataValue;
                var now = new Date(date[i].dataTime);
                var value = "";
                if(isNumber(v)) {
                    value = v;
                }
                var jjson = [now, value];
                // arr.push(jjson);
                //{库心：[1.4，1.5]}
                var keysite = sitemap[date[i].dataRemark];
                if (keysite in result){
                    result[keysite].push(jjson);
                }else {
                    result[keysite] = [jjson]
                }
            }
            // result['site'] = sitemap[date[i].dataRemark];
            // result['data'] = arr;
            return result;
            function isNumber(value) {
                return /^-?\d+(\.\d+)?$/.test(value);
            }
        },
        getSiteValue(){
            this.$http.get('/readMap/getsitevalueinsql.do',{emulateJSON:true}).then(function (res){
                this.siteValue = res.data;
                //曲线图默认选择第一个站点
                this.selectedsiteValue = [this.siteValue[0].id];
                // this.echarttype = this.echarttypeoptions[0].value;
            })
        },
        loadDate(t) {
            var beginDate = null;
            var endDate = null;
            if (this.dateValue != null) {
                beginDate = this.dateToString(this.dateValue[0]);
                endDate = this.dateToString(this.dateValue[1]);
            }
            var site = this.selectedsiteValue;
            if (this.echarttype === 'yancheng' && t === 1) {
                var siteids = [];
                for (let i = 0; i < this.siteValue.length; i++) {
                    siteids.push(this.siteValue[i].id);
                }
                this.selectedsiteValue = siteids;
            }
            this.$http.get('/hardware/getHarewaredData.do?languageType='+this.locals18n+'&site='+site+'&pre=' + this.siteTypeOptionValue.proNamech + "&begDate=" + beginDate + "&endDate=" + endDate, {emulateJSON: true}).then(function (res) {
                this.fullscreenLoading = true;
                this.pageCount = res.data.length;
                this.allData = res.data;
                if (res.data.length == 0) {
                    this.fullscreenLoading = false;
                    this.$message({
                        message: 'error',
                        type: 'error'
                    });
                } else {
                    this.fullscreenLoading = false;
                    // console.log(res.data);
                    // //统计图数据
                    var datasChart = this.fromatTimeData(res.data);
                    var duibidatas= this.fromatTimeDataUploadValue1(res.data);
                    var yanchengdatas= this.fromatTimeDatayancheng(res.data);
                    // var datasChartUpload= this.fromatTimeDataUploadValue(res.data);
                    var beginDate = this.dateToString(datasChart[0][0]);
                    var endDate = this.dateToString(datasChart[datasChart.length - 1][0]);
                    // this.myChart.clear();
                    var danweiy = res.data[0].danweiy;
                    var optiondata = this.dateToMap(res.data);
                    //alert(danweiy);
                    this.loadChart(datasChart, beginDate, endDate,duibidatas,yanchengdatas,danweiy,optiondata);
                    // //表格数据
                    // console.log(this.fromatTableData(res.data,1));
                    // console.log(res.data);
                    this.tableData = this.fromatTableData(res.data, 1);

                }

            });
        },
        fromatTimeDatayancheng(date) {
            //处理站点信息｛id:name｝
            var sitemap = {};
            for (let i = 0; i < this.siteValue.length; i++) {
                var site = this.siteValue[i];
                sitemap[site.id] = site.siteName;

            }
            var result = {};var arr = [];
            for (let i = 0; i < date.length; i++) {
                var v = date[i].dataValue;
                var keytime = new Date(date[i].dataTime);
                var value = "";
                if(isNumber(v)) {
                    value = v;
                }
                var site = sitemap[date[i].dataRemark];
                var jjson = [site, value];
                // arr.push(jjson);
                //{2024-9-1：[[库心，1.4]]}
                if (keytime in result){
                    result[keytime].push(jjson);
                }else {
                    result[keytime] = [jjson]
                }
            }
            return result;
            function isNumber(value) {
                return /^-?\d+(\.\d+)?$/.test(value);
            }
        },
        dateToString(date) {
            // 将data转化为String
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString();
            var day = (date.getDate()).toString();
            if (month.length == 1) {
                month = "0" + month;
            }
            if (day.length == 1) {
                day = "0" + day;
            }
            var dateTime = year + "-" + month + "-" + day;
            return dateTime;
        },
        dateToMap(data){
            var result = {};
            for (let index = 0; index< data.length; index++){
                var d = data[index];
                if (d.dataNameCh in result){
                    result[d.dataNameCh].value.push(d.dataValue);
                    result[d.dataNameCh].data.push([new Date(d.dataTime),d.dataValue]);
                } else {
                    result[d.dataNameCh] = {
                        "danweiy": d.danweiy,
                        "dataTime": new Date(d.dataTime),
                        "value":[d.dataValue],
                        "data":[[new Date(d.dataTime),d.dataValue]]
                    }
                }
            }
            return result;
        },
    }
});